<?php

namespace app\modules\api\controllers;


use app\models\ApiException;
use app\models\Package;
use app\models\Card;
use app\models\Isp;
use app\models\Agent;
use app\models\AgentPackage;
use app\models\UserCardRecharge;
use app\models\CardUsageSub;
use app\models\UserCardReserveRecharge;
use app\models\CardDatalog;
use Yii;
/**
 * 对外公开的接口
 * Class PublicController
 * @package app\modules\api\controllers
 */
class GprsController extends BasePublicController
{
    /**
     * 查询套餐
     * @return array
     */
    public function actionIndex()
    {
        $package_type = $this->get('type');
        switch ($package_type) {
            case '1':
                $type = '1';
                break;
            case '2':
                $type = '2';
                break;
            default:
                $type = '1';
                break;
        }
        //$type = $this->get('type');
        $iccid = $this->get('iccid');
        //$str = substr($iccid, 0,19);
        $iccidLength = strlen($iccid);
        if($iccidLength<19){
            $iccid = '-';
        }
        $pack = Card::find()->andWhere(['like','iccid',$iccid])->one();
        
        $res = (new \yii\db\Query())
        ->select(['package.id as id','package.name as name','package.data as data','package.price as price','agent_package.sale_price as sale_price','agent_package.cost_price as cost_price','agent_package.name as agent_package_name'])
        ->from('package')
        ->join('join','agent_package','agent_package.package_id=package.id')
        ->andWhere(['agent_package.agent_id'=> $pack['agent_id']])
        ->andFilterWhere(['package.type'=>$type])  
        ->andFilterWhere(['package.isp'=>$pack['isp_id']])
        ->groupBy('agent_package.package_id')
        ->all();
        
        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['data']=floatval($res[$key]['data']);
            $res[$key]['price']=floatval($res[$key]['price']);
            $res[$key]['sale_price'] = floatval($res[$key]['sale_price']);
            $res[$key]['cost_price'] = floatval($res[$key]['cost_price']);

        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }elseif(empty($res)){
            $data['code']="1001";
            $data['msg'] ="未查询到套餐";
            $data['data'] = "";
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];

    }
    public function actionChaxun()
    {
        // $package_type = $this->get('type');
        // switch ($package_type) {
        //     case '1':
        //         $type = '1';
        //         break;
        //     case '2':
        //         $type = '2';
        //         break;
        //     default:
        //         $type = '1';
        //         break;
        // }
        $type = $this->get('type');
        $iccid = $this->get('iccid');
        $iccidLength = strlen($iccid);
        if($iccidLength<19){
            $iccid = '-';
        }
        $pack = Card::find()->andWhere(['like','iccid',$iccid])->one();
        
        // $connection  = Yii::$app->db;
        // $sql     = "select * from package where status=1 ".$where." order by id desc";
        // $command = $connection->createCommand($sql);
        // $res     = $command->queryAll();
        $res = (new \yii\db\Query())
        ->select(['package.id as id','package.name as name','package.data as data','package.price as price','agent_package.sale_price as sale_price','agent_package.cost_price as cost_price','agent_package.name as agent_package_name'])
        ->from('package')
        ->join('join','agent_package','agent_package.package_id=package.id')
        ->andWhere(['agent_package.agent_id'=> $pack['agent_id']])
        ->andFilterWhere(['package.type'=>$type])  
        ->andFilterWhere(['package.isp'=>$pack['isp_id']])
        ->groupBy('agent_package.package_id')
        ->all();
        
        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['data']=floatval($res[$key]['data']);
            $res[$key]['price']=floatval($res[$key]['price']);
            $res[$key]['sale_price'] = floatval($res[$key]['sale_price']);
            $res[$key]['cost_price'] = floatval($res[$key]['cost_price']);

        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }elseif(empty($res)){
            $data['code']="1001";
            $data['msg'] ="未查询到套餐";
            $data['data'] = "";
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];

    }
    /**
     * 查询套餐显示代理成本价格
     * @return array
     */
    public function actionAgentpackage()
    {   
        $type = 1;
        $iccid = $this->get('iccid');
        $str = substr($iccid, 0,19);
        $pack = Card::find()->andWhere(['like','iccid',$str])->one();
    
        $res = (new \yii\db\Query())
        ->select(['package.id as id','package.name as name','agent_package.sale_price as sale_price','agent_package.name as agent_package_name'])
        ->from('package')
        ->join('join','agent_package','agent_package.package_id=package.id')
        ->andWhere(['agent_package.agent_id'=> $pack['agent_id']])
        ->andFilterWhere(['package.type'=>$type])  
        ->groupBy('agent_package.package_id')
        ->all();
        
        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['name'] = $res[$key]['name'];
            $res[$key]['sale_price'] = floatval($res[$key]['sale_price']);   

        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }elseif(empty($res)){
            $data['code']="1001";
            $data['msg'] ="未查询到套餐";
            $data['data'] = "";
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];

    }
    //代理商订购获取卡套餐
    public function actionAgentpackageall()
    {
        $type = 1;
        $iccid = $this->get('iccid');
        $str = substr($iccid, 0,19);
        $pack = Card::find()->andWhere(['like','iccid',$str])->one();
        $isp_id=$pack['isp_id'];
        if($pack['dgcs']==0 && empty($pack['package_id'])){
            
            //$filterwheres = ['package.type'=>'1'];
            //$filterwheres =['or' , 'package.type' => '1' , 'package.type' => '2'];
            $filterwheres = ['1','6'];
            $a = ['agent_package.isp'=>$isp_id];
        }elseif($pack['dgcs']>0 && empty($pack['package_id'])){
            //$filterwheres =['or' , 'package.type' => '1' , 'package.type' => '2'];
            $a=['agent_package.isp'=>$isp_id];
            $filterwheres =['package.type' => '1'];
        }elseif(!empty($pack['package_id'])){
            $a=['agent_package.isp'=>$isp_id];
            $filterwheres =['package.type' =>'2'];
        }else{
            $filterwheres=['package.type' =>'1'];
            $a='';
        }
        $res = (new \yii\db\Query())
            ->select(['package.id as id','package.name as name','package.type as type','agent_package.sale_price as sale_price','agent_package.cost_price as cost_price','agent_package.name as agent_package_name'])
            ->from('package')
            ->join('join','agent_package','agent_package.package_id=package.id')
            ->andWhere($a)
            ->andWhere(['package.type'=>$filterwheres])
            ->andWhere(['agent_package.agent_id'=> $pack['agent_id']])
            ->groupBy('agent_package.package_id')
            ->all();

        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['name'] = $res[$key]['name'];
            $res[$key]['sale_price'] = floatval($res[$key]['sale_price']);
            $res[$key]['cost_price'] = floatval($res[$key]['cost_price']);

        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }elseif(empty($res)){
            $data['code']="1001";
            $data['msg'] ="未查询到套餐";
            $data['data'] = "";
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
            'code'=>  $data['code'],
            'msg'=>  $data['msg'],
            'datas'=>  $data['data']
        ];

    }
    /**
     * 查询套餐
     *
     */
    public function actionGetpackage(){
        $package_id = $this->get('package_id');
        if(empty($package_id)){
            //$where=' and id='.$package_id;
        }else{
            $connection  = Yii::$app->db;
            $sql     = "select * from package where status=1 and id='".$package_id."' limit 1";
            $command = $connection->createCommand($sql);
            $selectIccid     = $command->queryOne();
            if(empty($selectIccid)){
                return[
                    'code'=>  1002,
                    'msg'=>  '未查询到数据',
                    'datas'=>  ''
                ];
                exit;
            }else{
                return[
                    'code'=>  1,
                    'msg'=>  '操作成功',
                    'datas'=>  $selectIccid
                ];
                exit;
            }
        }

    }
    /**
     * 创建订单（创建用户支付记录）
     *
     */
    public function actionCreateorder(){
        $iccid      = trim($_GET['iccid']);
        $packageid  = trim($_GET['packageid']);
        /*$money      = trim($_GET['money']);*/
        //if(empty($iccid) || empty($packageid) || empty($money)){
        if(!isset($iccid)){
            return[
                'code'=>  1001,
                'msg'=>  '参数不全',
                'datas'=>  ''
            ];
            exit;
        }
        //查询套餐详情
        $connection  = Yii::$app->db;
        $sql     = "select * from package where status=1 and packageid='".$packageid."' limit 1";
        $command = $connection->createCommand($sql);
        $selectIccid     = $command->queryOne();
        if(empty($selectIccid)){
            return[
                'code'=>  1002,
                'msg'=>  '未查询到数据',
                'datas'=>  ''
            ];
            exit;
        }
        //生成 用户订单
        $trade_no =date('YmdHis',time()).rand(1000, 9999);
        $res = $connection->createCommand()->insert('user_card_recharge',['iccid'=>$iccid,
            'packageid'=>$packageid,
            'money'=>$selectIccid['price'],
            'create_time'=>time(),
            'trade_no'=>$trade_no,
            'price'=>$selectIccid['isp_price'],
            'status'=>0,
            'uid'=>'1',
            'card_id'=>'39802',
            'term_length'=>'1',
            'term_length_unit'=>'1',
        ])->execute();
        //查出订单详情
        $idSql ="select * from user_card_recharge where status=0 and trade_no=".$trade_no;
        $res = $connection->createCommand($idSql)->queryOne();
        $session = \Yii::$app->session;
        $session->set("trade_no",$res['trade_no']);
        $session->set("order_id",$res['id']);
        //session('trade_no',$res['trade_no']);
        //session('order_id',$res['id']);
        //Yii::$app->session->addFlash('success', '数据已保存。');
        print_r($res);
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
            'code'=>  $data['code'],
            'msg'=>  $data['msg'],
            'data'=>  $data['data']
        ];
        exit;
    }
    /***
     * 支付成功回调（修改支付状态为已支付）
     */
    public function actionNotify(){
        $session = \Yii::$app->session;
        $order_id = $session['order_id'];
        if(empty($order_id)){
            return[
                'code'=>  1003,
                'msg'=>  '未获取到order_id',
                'datas'=>  ''
            ];
            exit;
        }
        $connection  = Yii::$app->db;
        $idSql ="select * from user_card_recharge where id=".$order_id;
        $res = $connection->createCommand($idSql)->queryOne();
        if($res['status']==1){
            return [
                'code'=>  1004,
                'msg'=>  '已经支付过了',
                'data'=>  ''
            ];
            exit;
        }
        $resUpdate = $connection->createCommand()->update('user_card_recharge',['status'=>'1',
            'pay_time'=>time()
        ],['id'=>$order_id]
        )->execute();
        if($resUpdate){
            return [
                'code'=>  1,
                'msg'=>  '操作成功',
                'data'=>  $resUpdate
            ];
            exit;
        }else{
            return [
                'code'=>  1001,
                'msg'=>  '操作失败',
                'data'=>  ''
            ];
            exit;
        }
    }
    /**
     * 返回数据
     */
    public function backData($code,$res='',$msg='操作成功'){
        if($code==1){
            $data['code']=$code;
            $data['msg']=$msg;
            $data['data']=$res;
            return $data;
            exit;
        }else{
            $data['code']=$code;
            $data['msg']=$msg;
            $data['data']=$res;
            return $data;
            exit;
        }
    }
    /**
     * 返回运营商id和名称
     */
    public function actionIspinfo(){
        $info = Isp::find()->select(['id','name'])->all();
        foreach ($info as $key => $value) {
            $info[$key]['id'] = $info[$key]['id'];
            $info[$key]['name'] = $info[$key]['name'];
        }
        if($info){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$info;
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];
    }
    //返回当前卡的运营商id和名称
    public function actionCardisp(){
        $iccid = $this->get('iccid');
        $pack = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $res = (new \yii\db\Query())
        ->select(['card.iccid as iccid','isp.id as ispid','isp.name as name'])
        ->from('card')
        ->join('join','isp','isp.id=card.isp_id')
        ->andWhere(['card.iccid'=> $pack['iccid']])
        ->all();
        foreach ($res as $key => $value) {
            $res[$key]['iccid'] = $res[$key]['iccid'];
            $res[$key]['ispid'] = $res[$key]['ispid'];
            $res[$key]['name'] = $res[$key]['name'];
        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];
    }
    //
    public function actionTaocan(){

        $res = (new \yii\db\Query())
        ->select(['package.id as id','package.name as name','package.data as data','package.price as price','agent_package.sale_price as sale_price','agent_package.cost_price as cost_price','isp.name as ispname','package.type as ptype'])
        ->from('package')
        ->join('join','agent_package','agent_package.package_id=package.id')
        ->join('join','isp','agent_package.isp=isp.id')
        ->andWhere(['agent_package.agent_id'=> 1])
        // ->andFilterWhere(['package.isp'=>$pack['isp_id']])
        ->all();
        print_r($res);
    }
    //返回当前代理商套餐的运营商
    public function actionAgentisp(){
        $iccid = $this->get('iccid');
        $agent = Card::find()->andWhere(['like','iccid',$iccid])->one();
        $agent_id = $agent['agent_id'];
        $res = (new \yii\db\Query())
        ->select(['isp.name as name','isp.id as id'])
        ->from('agent_package')
        ->join('join','isp','isp.id=agent_package.isp')
        ->andWhere(['agent_package.agent_id'=> $agent_id])
        ->groupBy('agent_package.isp')
        ->all();
        foreach ($res as $key => $value) {
            $res[$key]['name'] = $res[$key]['name'];
            $res[$key]['id'] = $res[$key]['id'];
        }
        if($res){
            $data['code'] = "1";
            $data['msg'] = "操作成功";
            $data['data'] = $res;
        }
        return [
            'code'  => $data['code'],
            'msg'   => $data['msg'],
            'datas' => $data['data']
        ];
    }
    
    
    //接收传递的运营商Id进行保存
    public function actionReceptisp(){
        $iccid = $this->get('iccid');
        $isp_id = $this->get('isp');
        $pack = Card::find()->andWhere(['like','iccid',$iccid])->one();
        if($pack['dgcs'] > 0){
            $result['code'] = "1001";
            $result['msg'] = "已有初始套餐，不能修改！";
            echo json_encode($result);
            exit;
        }
        Yii::$app->db->createCommand()->update('card', ['isp_id' => $isp_id], 'iccid = :iccid',['iccid' => $pack['iccid']])->execute();  
        return [
            'code' => '1',
            'msg'  =>  '操作成功',
        ];    
    }
   
    
    //定时任务执行预充值
    public function actionReserve(){
        $times = strtotime(date('Y-m-d'));
        $reserve = UserCardReserveRecharge::find()->where(['active_time'=>$times,'execute_status'=>2])->limit(1)->all();
        // $reserve = UserCardReserveRecharge::find()->where(['active_time'=>$times,'execute_status'=>2])->orderBy('id desc')->one();
        if(empty($reserve)){
            return ['code' => 2,'msg' => '暂时无数据执行'];
            exit;
        }
        foreach ($reserve as $key => $value) {
            $card = Card::findOne(['id'=>$value['card_id']]);
            $datas['card']['iccid'] = $card->iccid;
            $datas['term_length'] = $value['term_length'];
            $datas['price'] = $value['price'];
            $datas['money'] = $value['money'];
            $datas['trade_type'] = $value['trade_type'];
            $datas['trade_no'] = $value['order_sn'];
            $datas['trade_id'] = $value['order_sn'];
            $datas['app_id'] = "weixin";
            $datas['uid'] = $value['uid'];
            $datas['agent_id'] = $value['agent_id'];
            $datas['package_id'] = $value['package_id'];
            $datas['term_length_unit'] = $value['term_length_unit'];
            $datas['source'] = $value['source'];
            $datas['card_recharge_id'] = $value['card_recharge_id'];
            $data_string = json_encode($datas);
            $getMoneyUrl="http://cu.mangcaoiot.com/api/card/agent-reserve-recharge?version=1.0.0&app_id=weixin&nonce=123456&timestamp=1&sign=0123456789abcdef&token=";
            $iot_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MzU4MTM2NzYsInVpZCI6NCwiYXBwIjoid2VpeGluIn0=.6428835f2b1518367de235f6bd044eb41ae995f9b13dfe289faeb8448f6ce16f";
            $getMoneyUrl = $getMoneyUrl.$iot_token;
            $result = $this->UrlPost($getMoneyUrl,$data_string);
            $results = json_decode($result,true);
            if($results['error'] == ''){
                Yii::$app->db->createCommand()->update('user_card_reserve_recharge', ['execute_status' => 1], 'id = :id',['id' => $value['id']])->execute(); 
                return ['code' => 1,'iccid' => $card->iccid,'msg' => '执行预充值成功'];
            }

        }
        
    }
    
    public function UrlPost($url,$data_string){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
}
